package com.yanhao.viewmode

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import com.yanhao.repository.SearchRepository
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.*

class SearchViewModel(private val resp: SearchRepository) : BaseViewModel() {
    private val mChanncel = ConflatedBroadcastChannel<String>()

    fun queryParameterForDb(parameter: String) = mChanncel.offer(parameter)

    val searchResult = mChanncel.asFlow()
        // 避免在单位时间内，快输入造成大量的请求
        .debounce(800)
        //  避免重复的搜索请求。假设正在搜索 dhl，用户删除了 l  然后输入 l。最后的结果还是 dhl。它就不会再执行搜索查询 dhl
        // distinctUntilChanged 对于 StateFlow 任何实例是没有效果的
        .distinctUntilChanged()
        .flatMapLatest { search -> // 只显示最后一次搜索的结果，忽略之前的请求
//            pokemonRepository.fetchPokemonByParameter(search).cachedIn(viewModelScope)
//            resp.search()
            resp.search(0, search)
        }.catch { e: Throwable ->
            //  异常捕获
            errorCatch(e)
        }.asLiveData()
}

class SearchViewModelFactory : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(SearchViewModel::class.java)) {
            return SearchViewModel(resp = SearchRepository()) as T
        }
        throw IllegalArgumentException("不能找到 SearchViewModelFactory")
    }

}